package com.example.chdemo.Controller;

import com.example.chdemo.Dao.Person;
import com.example.chdemo.Service.PersonService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/")
public class PersonController {

    @Autowired
    private PersonService personService;

    @GetMapping
    public String getAllListOne(Model model){
        PageInfo<Person> pageInfo = personService.getAllPage(1,5);
        model.addAttribute("pageInfo",pageInfo);
        return "/clint/index";
    }

    @RequestMapping("/{pageNum}/{pageSize}")
    public String getAllList(@PathVariable(value = "pageNum") Integer pageNum,
                             @PathVariable(value = "pageSize") Integer pageSize,
                             Model model){
        PageInfo<Person> pageInfo = personService.getAllPage(pageNum,pageSize);
        model.addAttribute("pageInfo",pageInfo);
        System.out.println(pageNum);
        System.out.println(pageSize);
        System.out.println(pageInfo);

        return "/clint/index";
    }

    @RequestMapping("{id}")

    public String del(@PathVariable(value = "id") Integer id,Map<String,Object> map){
        int zt = personService.del(id);
        if(zt == 1){
            map.put("code",1);
            map.put("msg","删除成功");
        }else {
            map.put("code",0);
            map.put("msg","删除失败");
        }
        return "redirect:/";
    }

    @GetMapping("/inst")
    public String inst(){
        return "/clint/inst";
    }
//    @GetMapping("/edit/{id}")
//    public String edit(@PathVariable(value = "id") Integer id,Model model){
//        Person person = personService.getOne(id);
//        model.addAttribute("editOne",person);
//        return "/clint/edit";
//    }
    @PostMapping("/inst")
    public String add(Person person){
        System.out.println(person);
        personService.insert(person);
        return "redirect:/";
    }

    @RequestMapping(value = "/up/{id}",method = RequestMethod.GET)
    public String upDataShow(@PathVariable(value = "id") Integer id,Model model){
        Person person = personService.getOne(id);
        model.addAttribute("editOne",person);
        System.out.println(person);
        return "/clint/add";
    }

    @RequestMapping(value = "/up/{id}",method = RequestMethod.POST)
    public String upData(@PathVariable(value = "id") Integer id,Person person){
        person.setId(id);
        personService.upData(person);
        return "redirect:/";
    }
}
